package com.ccsoft.multithread.test;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author chanchaw
 * @create 2022-08-05 14:10
 * 使用3个线程分别打印：a,b,c。要求交替执行，累计打印5组
 * 本案例使用 ReentrantLock 多条件变量的特性
 */
public class No302AlternateAwaitSignal {
    public static void main(String[] args) {
        AwaitSignal awaitSignal = new AwaitSignal(5);
        Condition a = awaitSignal.newCondition();
        Condition b = awaitSignal.newCondition();
        Condition c = awaitSignal.newCondition();

        new Thread(()->{
            awaitSignal.doWork("a",a,b);
        },"t1").start();

        new Thread(()->{
            awaitSignal.doWork("b",b,c);
        },"t2").start();

        new Thread(()->{
            awaitSignal.doWork("c\n",c,a);
        },"t3").start();

        awaitSignal.lock();
        try {
            a.signal();
        }finally {
            awaitSignal.unlock();
        }
    }
}

class AwaitSignal extends ReentrantLock {
    private int loopNumber = 1;

    public AwaitSignal(int loopNumber) {
        this.loopNumber = loopNumber;
    }

    public void doWork(String printString, Condition currentCondition,Condition nextCondition){
        for (int i = 0; i < loopNumber; i++) {
            lock();
            try {
                currentCondition.await();
                System.out.print(printString);
                nextCondition.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                unlock();
            }
        }
    }
}
